let layerIndex;
/**
 * 弹出学生新增/更新对话框
 */
function showStudentDlg(id){

    let title = "新增学生"
    if(id){

        //执行编辑功能
        title = "编辑学生"
        $("#formId").css("display", "block");
        //读取学生信息,并赋值
        $.ajax({
            url:"/api/student/" + id,
            method: "GET"
        }).done(result =>{

            console.log(result)

            // 遍历 result 对象并将其赋值填充到 #studForm 表单中
            $.each(result, function(key, value){

                var field = $('#studForm [name="' + key + '"]');

                if (field.is(':radio')) {
                    field.filter('[value="' + value + '"]').prop('checked', true); // 选中对应的单选按钮
                }
                else if (field.is(':checkbox')){
                    field.prop('checked', value === "yes"); //选中复选框
                }
                else {
                    field.val(value); // 填充文本框或者其他字段
                }
            });
        })


    }else{
        //执行新增功能
        $("#studForm")[0].reset();
        $("#formId").css("display", "none");
    }
    layerIndex = layer.open({
        type: 1,
        title: title,
        area: ['520px', 'auto'],
        content: $('#studForm') //捕获层
    });
}

function getSearchCondition(){

    let formData={}
    //遍历每个输入元素，将其值储存到 formData 对象中
    $('#queryForm').find('input, select').each(function(){
        let name = $(this).attr('name'); //获取元素的 name 属性
        let value = $(this).val(); //获取元素的值

        //只有属性存在且不会添加到 formData 中
        if(name && value){
            formData[name] = value;
        }
    });

    return formData
}


layui.use(function (){
    //(1)验证表单是否合法
    layui.form.on('submit(stud-dlg)', function(data){
        event.preventDefault(); // 阻止默认表单提交

        commitStuDlg();
    })

    //(2)表格初始化
    const table = layui.table;

    let student = getSearchCondition();

    //创造渲染示例
    table.render({
        elem: '#tbStudent',
        url: '/api/student/getbypage',  //  此处为静态模拟器，实际使用是需换成真实接口

        method: "POST",
        contentType: 'application/json', //  确保以 JSON 格式发送
        where: {"data": student},

        page: true,
        cols: [[
            {type: 'checkbox', fixed: 'left'},
            {field: 'id', fixed: 'left', width: 80, title: 'id', sort: true},
            {field: 'name', title: '姓名'},
            {
                field: 'sno',
                title: '学号',
                width: 150,
            },
            {field: 'sex', width: 80, title: '性别', sort: true,
                templet: d => d.sex === 1 ? '男' : (d.sex === 0 ? '女' : '未知'),
            },

            {field: 'age', width: 100, title: '年龄', sort: true},

            {field: 'right', title: '操作', width: 134, minWidth: 125, templet: '#editTemplate'}

        ]],
        done: function (rs){

        }
    });

    // 触发单元格工具
    table.on('tool(tbStudent)', function(obj){

        var data = obj.data;
        if(obj.event === 'edit'){
            console.log(data.id);
            showStudentDlg(data.id);
        }
    })

});


function search(){
    let student = getSearchCondition();

    const table = layui.table;
    table.reloadData("tbStudent", {
        where: {data:student}
    });
    console.log("where condition:" + JSON.stringify(student))
}

function commitStuDlg(){

    const table = layui.table;

    let formData = $("#studForm").serialize();
    let id = $("#id").val()
    if(id != null && id != ""){
        //更新学生
        $.ajax({
            url: "/api/student/update",
            method: "PUT",
            data: formData
        }).done(result =>{
            console.log(result);
            if(result.id){
                //(3)读取并刷新原来的在读学生表
                table.reloadData('tbStudent')

                //(4)关闭弹出层
                console.log("updated successfully")
                if(layerIndex)
                    layer.close(layerIndex)
            }



        }).fail((jqXHR, textStatus, errorThrown) =>{
            console.error("Request failed: " + textStatus + " - " + errorThrown);
            //处理错误逻辑
            alert("An error occurred. Please try again.");
        });
    }
    else {
        //新增学生步骤

        //(1)验证表单是否合法 layui替我们完成了

        //(2)将表单发送到服务器的insert中，把提交按钮禁用

        $.ajax({
            url: "/api/student/add",
            method: "POST",
            data: formData
        }).done(result =>{
            console.log(result);
            if(result.id){
                //(3)读取并刷新原来的在读学生表
                table.reloadData('tbStudent');

                //(4)关闭弹出层
                console.log("added successfully")
                if(layerIndex)
                    layer.close(layerIndex)
            }
        }).fail((jqXHR, textStatus, errorThrown) =>{
            console.error("Request failed: " + textStatus + " - " + errorThrown);
            //处理错误逻辑
            alert("An error occurred. Please try again.");
        });
    }

    $("#btnOK").prop("disabled", true).addClass("layui-btn-disabled"); //禁用按钮
}
function deleteConfirm(){
    const table = layui.table;

    //获取表单状态
    const checkStatus = table.checkStatus('tbStudent');


    console.log(checkStatus);
    $.each(checkStatus.data, function (index, element){

        $.ajax({
            url: "/api/student/delete/" + element.id,
            method: "DELETE",
        }).done(result =>{
            table.reloadData("tbStudent");
        })
    });

}



